var videos;
var videoIndex;
function showstatus(){
	$("flashcontent").innerHTML = "";
	$("flashcontent").setStyle("display", "none");
	$("log").setStyle("display", "block");
}
function updatestatus(str){
	//$("flashcontent").setStyle("display", "none");
	//$("log").setStyle("display", "block");
	$("log").innerHTML = str;
}
function setAudioTime(time){
	//so.setProxy('youtubevid', SWF_PATH+'swfobject_js_gateway.swf');
	//var at = so.call('setAudioTime', time);
	//return (new Date().getTime());
	//$('youtubevid').setAudioTime(time);
}
function setAudioTime2(time){
/*	//so.setProxy('youtubevid', SWF_PATH+'swfobject_js_gateway.swf');*/
	var at = so.call('setAudioTime2', time);
	return (new Date().getTime());
}
function startVideo(){
	//alert(videoIndex+ " : "+videos.length);
    if(videos.length > 0)
	playVideo(videos[videoIndex].id, videos[videoIndex].title);
}
function skipForward(){
	var lastIndex = videos.length -1;
	if(videoIndex < lastIndex){
		videoIndex++;	
		startVideo();		
	}
	if(videoIndex == lastIndex)
		$("bt-forward").className = "last";
	else
		$("bt-forward").className = "";
}

function searchCompleted(HTML){

    videos = new Array();

	if(!HTML) return;
    
   // var matches = HTML.match(/watch\?v=(.)*?\"/gi); /* " */
    
    var matches = HTML.match(/watch\?v(.)*>/gi); /* " */
    
    // step 2 for v id \?v=.*?"
    // step 3 for title title=".*?"
	alert("number of v matches "+ matches.length);
    
    var vid = ""
    var title = ""
	for(var i in matches){		
        try{
            vid = matches[i].match(/\?v=.*?"/)[0].replace('?v=', "").replace('"', ""); /* "' */            
            title = matches[i].match(/title=".*?"/)[0].replace('title="', "").replace('"', ""); /* "' */
        }catch(e){
            //alert("error getting vid regex "+e);
        }
        if(! arraySearch(videos, vid) && vid.length == VIDEO_ID_LENGTH){ 
            
            videos.push({id:vid, title:title});    
        }
    } 
    
 //   writelog({id:videos[0].id, title:videos[0].title});	
    videoIndex = 0;
	startVideo();   
    
      
}
function arraySearch(array, needle) {
  //  alert("search "+needle);
   	var found = false;
    for(var i=0; i < array.length; i++){
       	if( array[i].id == needle){
            found = true;
          //  alert("found "+needle);
        }else{
          //  alert("not found "+i.id+" "+needle);
        }
    }        
    return found;        	
}


function playVideo(video_id, title){
    var tube_url = YOUTUBE_PATH+"watch?v="+video_id;
    writelog({tube_url2:tube_url});  
    var curlUrl = CURL+tube_url+" | grep -o '&t=.*&rv'"
    writelog({"curlUrl: ":curlUrl});    
	updatestatus("Getting fullscreen video.");
    
    var responseText = "";
    var myCommand = widget.system(curlUrl, function(){});
    myCommand.onreadoutput = function(event){
        responseText = responseText+event
        updatestatus("Video found");
        writelog({result:"Video Result found"});
       // alert("responseText length: "+responseText.length);
       // alert("responseText: "+responseText);       
        var matches = responseText.match( /&t=(.)*?&/gim );
        if(matches == null){
                //alert(responseText)
                updatestatus("Null match.");
                 writelog({matches:"Null matches"});
                 playVideo(video_id, title)
        }
        else if(matches.length < 1){            
            updatestatus("no matches found");
            writelog({matches:"no matches found"});
        }else{          
            var t = matches[0].substring(3, matches[0].length -1 )
            writelog({"t: ":t});
            /*    try{
                    var titlematch = responseText.match(/<h1[^]*>(.*?)<\/h1>/gim); 
                    var str = titlematch[0].replace("</h1>", "");
                    var parts = str.split(">");
                    title = parts[1];
                    alert("title "+title);
                }catch(e){
                    alert(e);
                } */
              
                updatestatus("Match found");
                 writelog({matches:"Match found"});
                updateTitle(title, unescape(tube_url));
                embedTubePlayer(video_id, t)           
            }
    };   
        
}
    
function playVideoOLD(video_id, title){
    var tube_url = YOUTUBE_PATH+"watch?v="+video_id;
    writelog({tube_url2:tube_url});
    getTubeHtml(tube_url);
	updatestatus("Getting fullscreen video.");
    
    var myAjax = new Ajax( tube_url , {
		method: PROXY_URL ? 'POST' : 'POST',
       
        onFailure: function(e, v) { alert('Request failure. '+e+" v:"+v); }, 
		onComplete: function(responseText, responseXML){
			updatestatus("Video found");
            writelog({result:"Video Result found"});
            alert("response text "+responseText);
 //length_seconds=387&t=vjVQa1PpcFN48kGj5Cg6WcnYYY3nQP9BnhKcZP1QCOw%3D&rv.6.id=aTObBNQ1anQ&cafe_experiment_id=&rv.6.view_count=407881&rv.3.
            var matches = responseText.match(/"t=": "(.*?)"/g); /* " */
            
            if(matches == null){
                //alert(responseText)
                updatestatus("Null match.");
                 writelog({matches:"Null matches"});
                 playVideo(video_id, title)
            }
            else if(matches.length < 1){
               
                updatestatus("no matches found");
                 writelog({matches:"no matches found"});
            }else{
                
                var t = matches[0]
                t = t.replace('"t": "', '');
                t = t.replace('"', '');
                try{
                    var titlematch = responseText.match(/<h1[^]*>(.*?)<\/h1>/gim); /* " */
                    var str = titlematch[0].replace("</h1>", "");
                    var parts = str.split(">");
                    title = parts[1];
                    alert("title "+title);
                }catch(e){
                    alert(e);
                }
              
                updatestatus("Match found");
                 writelog({matches:"Match found"});
                updateTitle(title, unescape(tube_url));
                embedTubePlayer(video_id, t)           
            }
        }
    }).request();
}



function embedTubePlayer(video_id, t_id){
//alert(SWF_PATH+SWF_PLAYER)
    so = new SWFObject(SWF_PATH+SWF_PLAYER, "youtubevid", "100%", "100%", "8");
	//so.addVariable( 'video_id', video_id );
    //so.addVariable( 't', t_id );
    //http://youtube.com/get_video?video_id=-byGaomKP3w&t=vjVQa1PpcFOpOgwGH8aHQat0sZ0d0Q1uJ9NZUrMZJWU%3D
    
    var videoURL = "http://youtube.com/get_video?video_id="+video_id+"&t="+t_id;
    alert("videoURL " + videoURL);
	so.addVariable( 'flvurl', escape(videoURL) );
	so.addVariable( 'set_volume', VOLUME );
	if(TRY_SYNC){
		alert("seek to "+trackinfo.time ); // dont use the stored currentsong data
		so.addVariable( 'seek_to_sec', (trackinfo.time + 2) );
	}else{
		so.addVariable( 'seek_to_sec', -1 );
	}
	so.addVariable( 'audio_totaltime', (currentsong.totaltime) );
	so.addVariable( 'video_smoothing', "true" );
	so.addParam("allowScriptAccess", "always");
	so.write("flashcontent");
    
    $("flashcontent").setStyle("display", "block");
	$("log").setStyle("display", "none");
    
    attachControls();
}


